<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            />
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
          >
            添加用户
          </el-button>
        </el-col>
      </el-row>
      <!--用户列表区域-->
      <el-table
        v-loading="loading"
        :data="userList"
        border
        stripe
        ref="table"
      >
        <el-table-column
          type="index"
          label="#"
        />
        <el-table-column
          label="账号"
          prop="username"
        />
        <el-table-column
          label="邮箱"
          prop="email"
        />
        <el-table-column
          label="创建时间"
          prop="create_time"
        >
          <template slot-scope="scope">
            {{ scope.row.create_time | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column
          label="电话"
          prop="mobile"
        />
        <el-table-column
          label="角色"
          prop="role_name"
        />
        <el-table-column label="状态">
          <!-- eslint-disable-next-line -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="usersStateChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180px"
        >
          <!-- eslint-disable-next-line -->
          <template slot-scope="scope">
            <!--修改按钮-->
            <el-tooltip
              class="item"
              effect="dark"
              content="修改"
              placement="top"
            >
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="showEditDialog(scope.row.id)"
              />
            </el-tooltip>
            <!--删除按钮-->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="removeUserById(scope.row.id)"
              />
            </el-tooltip>
            <!--分配角色按钮-->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="setRole(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </el-card>
    <!--添加用户的对话框-->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      @close="addDialogClosed"
    >
      <!--内容主体区域-->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item
          label="账号"
          prop="username"
        >
          <el-input
            v-model="addForm.username"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input
            v-model="addForm.password"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input
            v-model="addForm.email"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="手机"
          prop="mobile"
        >
          <el-input
            v-model="addForm.mobile"
            clearable
          />
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUser"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!--修改用户的对话框-->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
      width="30%"
      @click="editDialogClosed"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="70px"
      >
        <el-form-item label="账号">
          <el-input
            v-model="editForm.username"
            disabled
          />
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="editForm.email"/>
        </el-form-item>
        <el-form-item
          label="手机"
          prop="mobile"
        >
          <el-input v-model="editForm.mobile"/>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editUserInfo"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!--分配角色对话框-->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%" @close="setRoleDialogClosed"
      :close-on-click-modal="false">
      <div>
        <p>当前的用户:{{userInfo.username}}</p>
        <p>当前的用户:{{userInfo.role_name}}</p>
        <p>分配新角色:
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'Users',
    data() {
      return {
        // eslint-disable-next-line
        //获取用户列表的参数对象
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 10
        },
        userList: [],
        total: 0,
        loading: false,
        // eslint-disable-next-line
        //控制添加用户对话框的显示与隐藏
        addDialogVisible: false,
        // eslint-disable-next-line
        //添加用户的表单数据
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        // eslint-disable-next-line
        //添加表单验证规则的对象
        addFormRules: {
          username: [
            { required: true, message: '请输入登录名称', trigger: 'blur' },
            // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
            {
              validator: (rule, value, callback) => {
                const email = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/// 邮箱验证
                const MobileRegex = /0?(13|14|15|18)[0-9]{9}/// 手机号码验证
                if (!MobileRegex.test(value) && !email.test(value)) {
                  this.flag = false
                  callback(new Error('请输入手机号码或邮箱！'))
                }
                callback()
              },
              trigger: 'blur'
            }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                const email = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/// 邮箱验证
                if (!email.test(value)) {
                  callback(new Error('邮箱格式不正确！'))
                }
                callback()
              },
              trigger: 'blur'
            }
          ],
          mobile: [
            { required: true, message: '请输入号码', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                const MobileRegex = /0?(13|14|15|18)[0-9]{9}/// 手机号码验证
                if (!MobileRegex.test(value)) {
                  callback(new Error('手机号码格式错误!！'))
                }
                callback()
              },
              trigger: 'blur'
            }
          ]
        },
        // eslint-disable-next-line
        //控制修改用户对话框的显示与隐藏
        editDialogVisible: false,
        // eslint-disable-next-line
        //查询到的用户信息对象
        editForm: {},
        // eslint-disable-next-line
        //修改表单的验证规则对象
        editFormRules: {
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                const email = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/// 邮箱验证
                if (!email.test(value)) {
                  callback(new Error('邮箱格式不正确！'))
                }
                callback()
              },
              trigger: 'blur'
            }
          ],
          mobile: [
            { required: true, message: '请输入号码', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                const MobileRegex = /0?(13|14|15|18)[0-9]{9}/// 手机号码验证
                if (!MobileRegex.test(value)) {
                  callback(new Error('手机号码格式错误!！'))
                }
                callback()
              },
              trigger: 'blur'
            }
          ]
        },
        // 控制分配角色对话框的显示与隐藏
        setRoleDialogVisible: false,
        // 需要被分配角色的用户信息
        userInfo: '',
        // 所有角色的数据列表
        rolesList: [],
        // 已选中的角色id值
        selectRoleId: ''
      }
    },
    created() {
      this.getUserList()
    },
    methods: {
      // eslint-disable-next-line
      //获取用户列表数据
      async getUserList() {
        const { data: res } = await this.$http.get('users', {
          params: this.queryInfo
        })
        if (res.meta.status !== 200) {
          this.loading = true
          return this.$message.error(res.meta.msg)
        }
        // eslint-disable-next-line
        this.userList = res.data.users
        this.total = res.data.total
      },
      // eslint-disable-next-line
      //时间过滤
      dateFormat(dateStr) {
        const dt = new Date(dateStr)
        const y = dt.getFullYear()
        const m = dt.getMonth() + 1
        const d = dt.getDate().toString().padStart(2, 0)
        const h = dt.getHours().toString().padStart(2, 0)
        const f = dt.getMinutes().toString().padStart(2, 0)
        return `${y}-${m}-${d} ${h}:${f}`
      },
      // eslint-disable-next-line
      //监听 pagesize 改变的事件
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getUserList()
      },
      // eslint-disable-next-line
      //监听 页码值改变的事件
      handleCurrentChange(newSize) {
        this.queryInfo.pagenum = newSize
        this.getUserList()
      },
      // eslint-disable-next-line
      //监听 switch 开关状态的改变
      async usersStateChange(userInfo) {
        const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        if (res.meta.status !== 200) {
          userInfo.mg_state = !userInfo.mg_state
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
      },
      // eslint-disable-next-line
      //监听 添加用户对话框的关闭事件
      addDialogClosed() {
        this.$refs.addFormRef.resetFields()
      },
      addUser() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) {
            return this.$message.error('数据验证失败!')
          }
          // eslint-disable-next-line
          //发起添加用户请求
          const { data: res } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.addDialogVisible = false
          this.getUserList()
        })
      },
      // eslint-disable-next-line
      //展示编辑用户的对话框
      async showEditDialog(id) {
        const { data: res } = await this.$http.get('users/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.editForm = res.data
        this.editDialogVisible = true
      },
      // eslint-disable-next-line
      //监听修改用户对话框的关闭事件
      editDialogClosed() {
        this.$refs.editFormRef.resetFields()
      },
      // eslint-disable-next-line
      //修改用户信息并提交
      editUserInfo() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) {
            return this.$message.error('数据验证失败!')
          }
          const { data: res } = await this.$http.put(`users/${this.editForm.id}`, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.editDialogVisible = false
          this.getUserList()
          return this.$message.success(res.meta.msg)
        })
      },
      // eslint-disable-next-line
      //根据id删除对应的用户
      async removeUserById(id) {
        /*
          弹框询问用户是否删除用户
         */
        const result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        /*
          如果用户确认删除,则返回字符串confirm
          如果用户取消删除,则返回字符串cancel
         */
        if (result !== 'confirm') {
          return this.$message.info('已取消删除')
        }
        this.deleteUser(id)
      },
      // eslint-disable-next-line
      //发起添加用户请求
      async deleteUser(id) {
        const { data: res } = await this.$http.delete(`users/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getUserList()
      },
      // 展示分配角色的对话框
      async setRole (userInfo) {
        this.userInfo = userInfo
        // 展示对话框前获取所有的角色列表
      const { data: res } = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.rolesList = res.data
        this.setRoleDialogVisible = true
      },
      // 点击按钮分配角色
      async saveRoleInfo () {
        if (!this.selectRoleId) {
          return this.$message.error('请选择要分配的角色!')
        }
        const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectRoleId })

        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getUserList()
        this.setRoleDialogVisible = false
      },
      // 监听分配角色框对话框的关闭事件
      setRoleDialogClosed () {
        this.selectRoleId = ''
        this.userInfo = {}
      }
    }
  }
</script>

<style lang="less" scoped>
</style>
